package com.modules.upms.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.util.R;
import com.common.web.BaseController;
import com.modules.upms.entity.SysDept;
import com.modules.upms.entity.SysDict;
import com.modules.upms.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 */
@RestController
@RequestMapping(value = "/sys/dict")
public class SysDictController extends BaseController {

    @Autowired
    private SysDictService sysDictService;

    /**
     * 获取指定编码下的所有子字典
     *
     * @param type 编码
     * @return
     */
    @GetMapping(value = "/getListByType")
    public R<List<SysDict>> getListByType(String type) {
        return R.success(sysDictService.getListByType(type));
    }

    /**
     * 分页查询字典信息
     *
     * @param query 查询对象
     * @return 分页对象
     */
    @GetMapping(value = "/listPage")
    public R<IPage> listPage(Page page, SysDict query) {
        return R.success(sysDictService.getPage(page, query));
    }

    /**
     * 所有的类型
     *
     * @return 所有的类型
     */
    @GetMapping(value = "/listType")
    public R<List<SysDict>> listType() {
        return R.success(sysDictService.getListType());
    }

    /**
     * 添加字典
     *
     * @param sysDict 字典信息
     * @return success、false
     */
    @PostMapping(value = "/save")
    @CacheEvict(value = "dict_details", key = "#sysDict.type")
    public R<Boolean> save(@RequestBody SysDict sysDict) {
        return new R<Boolean>(sysDictService.saveOrUpdate(sysDict));
    }

    /**
     * 更新排序
     * @param list
     * @return
     */
    @PostMapping(value = "/updateSorts")
    public R<Boolean> updateSorts(@RequestBody List<SysDict> list){
        sysDictService.updateSorts(list);
        return R.success();
    }

    /**
     * 更新状态
     * @param sysDict
     * @return
     */
    @PostMapping(value = "/updateStatus")
    public R<SysDept> updateStatus(@RequestBody SysDict sysDict){
        sysDictService.updateStatus(sysDict);
        return R.success();
    }

    /**
     * 删除字典，并且清除字典缓存
     *
     * @param id   ID
     * @param type 类型
     * @return R
     */
    @DeleteMapping(value = "/{id}/{type}")
    @CacheEvict(value = "dict_details", key = "#type")
    public R<Boolean> deleteDict(@PathVariable Integer id, @PathVariable String type) {
        return new R<>(sysDictService.deleteById(id));
    }
}
